package com.xiaobai.netease_news.thread;

import android.content.Context;
import android.os.AsyncTask;
import android.widget.BaseAdapter;
import android.widget.Toast;

import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.xiaobai.netease_news.adapters.VideoAdapter;
import com.xiaobai.netease_news.client.ClientAPI;
import com.xiaobai.netease_news.constants.Constant;
import com.xiaobai.netease_news.model.Video;

import org.json.JSONObject;

import java.util.List;

/**
 * Created by PiscesQ on 2015/6/25.
 */
public class VideoAsyncTask extends AsyncTask<String, Void, List<?>> {

    private Context context;
    private BaseAdapter adapter;
    private PullToRefreshListView ptrListView;
    private String pullDirection = Constant.PULLDOWN;

    public VideoAsyncTask(Context context, BaseAdapter adapter, PullToRefreshListView ptrListView){
        this.context = context;
        this.adapter = adapter;
        this.ptrListView = ptrListView;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected List<?> doInBackground(String... params) {
        List<?> ret = null;
        int length = params.length;
        switch(length){
            case 1: //长度为1，则为完整的链接，不需要拼接
                JSONObject jsonObject = ClientAPI.getData(params[0]);
                if (jsonObject != null) {
                    ret = ClientAPI.handleVideoJSON(jsonObject);
                }
                break;
            case 2:
                jsonObject = ClientAPI.getData(params[0]);
                if (jsonObject != null) {
                    ret = ClientAPI.handleVideoJSON(jsonObject);
                }
                pullDirection = params[1];
                break;
        }
        return ret;
    }

    @Override
    protected void onPostExecute(List<?> objects) {
        if(adapter instanceof VideoAdapter && objects != null){
            VideoAdapter videoAdapter = (VideoAdapter) adapter;

            if(pullDirection.equals(Constant.PULLUP)){
                videoAdapter.addVideoList((List<Video>) objects);
            }else if(pullDirection.equals(Constant.PULLDOWN)){
                videoAdapter.setVideoList((List<Video>) objects);
            }
            videoAdapter.notifyDataSetChanged();

        }else{
            Toast.makeText(context, "网络未连接！", Toast.LENGTH_SHORT).show();
        }
        ptrListView.onRefreshComplete();
    }
}
